package com.darin.camera;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Log;

import com.google.zxing.LuminanceSource;
/**
 * 
 * @author Jianfeng.Lao
 *
 */
public class BitmapLuminanceSource extends LuminanceSource {
	private static final String TAG = "BitmapLuminanceSource";
	private byte bitmapPixels[];
	private int pixels[];
	private Bitmap bitmap;

	protected BitmapLuminanceSource(Bitmap bitmap) {
		super(bitmap.getWidth(), bitmap.getHeight());
		pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
		this.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
		this.bitmap=bitmap;
		bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
		
		// 32bit bitmap to 8bit gray bitmap 
		for (int i = 0; i < pixels.length; i++) {
			bitmapPixels[i] = (byte) pixels[i];
		}
	}

	@Override
	public byte[] getMatrix() {
		// 返回我们生成好的像素数据
		return bitmapPixels;
	}

	@Override
	public boolean isCropSupported() {
		return true;
	}

	@Override
	public byte[] getRow(int y, byte[] row) {
		// 这里要得到指定行的像素数据
		System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());
		return row;
	}

	public Bitmap renderCroppedGreyscaleBitmap() {
		if(bitmap!=null){
			return bitmap;
		}
		int width = getWidth();
		int height = getHeight();
		int[] newPixels = new int[width * height];
		// byte[] rgb = bitmapPixels;
		int[] rgb = pixels;
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		bitmap.setPixels(rgb, 0, width, 0, 0, width, height);
		return bitmap;
	}

	public int rgba2gray(int R, int G, int B, int A) {
		int gray = (int) ((float) R * 0.299f + (float) G * 0.587f + (float) B * 0.114f);
		return A | (gray << 16) | (gray << 8) | gray;
	}

}
